//单选列表
const zbAsRadio = function(){
    this.onSelected = null; //点击确认后执行回调
    this.isConfirm = 0; //是否已点击过确认按钮, 防止频繁点击
    
    //浮层模板
    this.tpl = '<div id="zbAsRadio" class="zb-flex-col-bottom zb-flex-nowrap zb-width-r100">\
        <div id="zbASMask" class="zb-flex-grow1"></div>\
        <div id="zbASBox" class="zb-flex-col-between zb-flex-stretch">\
          <div id="zbASTitle" class="zb-text-center"></div>\
          <div id="zbASBody" class="zb-scroll-y"></div>\
         </div>\
         <input type="hidden" id="zbInput" value="">\
        </div>';

    this.init = function (title='') {
        let flag = document.getElementById('zbAsRadio');
        if (flag == null) {
            //初始化css
            this.initCss();

            //初始模板, 绑定事件
            let body = document.getElementsByTagName('body')[0];
            let node = this.htmlToNode(this.tpl);
            node.querySelector('#zbASMask').addEventListener('click', this.hide.bind(this));
            body.appendChild(node);
        }

        document.getElementById('zbASTitle').innerText = title;
    }

    this.htmlToNode = function (html) {
        let div = document.createElement('div');
        div.innerHTML = html;
        return div.firstElementChild;
    }

    //隐藏弹出层
    this.hide = function () {
        document.getElementById('zbAsRadio').style.height = '0';
        document.getElementById('zbASBody').innerHTML = '';
        this.isConfirm = 0;
    }

    //显示弹出层
    this.show = function () {
        document.getElementById('zbAsRadio').style.height = '100%';
    }

    //点击确认按钮触发执行
    this.confirm = function () {
        if (this.isConfirm === 1) {
            console.log('重复点击');
            return;
        }
        this.isConfirm = 1;
        let input = document.getElementById('zbInput');
        let obj = this.decodeObj(input.value);
        input.value = ''; //清空已存储的数据
        this.hide();
        if (typeof this.onConfirm === 'function') {
            this.onConfirm(obj);
        }
    }

    //清除所有的class
    this.clearClass = function(id) {
        let obj = document.getElementById(id);

        let cls = [];
        for (let i=0; i<obj.classList.length; i++) {
            cls.push(obj.classList[i]);
        }

        for (let i=0; i<cls.length; i++) {
            obj.classList.remove(cls[i]);
        }
    }

    //生成样式
    this.initCss = function() {
        let style = document.createElement('style');
        style.innerText =
            '.zb-flex-col-top {display:flex;flex-direction:column;justify-content:flex-start}'+
            '.zb-flex-col-bottom {display:flex;flex-direction:column;justify-content:flex-end}'+
            '.zb-flex-col-between {display:flex;flex-direction:column;justify-content:space-between}'+
            '.zb-flex-col-center {display:flex;flex-direction:column;justify-content:center}'+
            '.zb-flex-col-around {display:flex;flex-direction:column;justify-content:space-around}'+
            '.zb-flex-row-left {display:flex;flex-direction:row;justify-content:start}'+
            '.zb-flex-row-center {display:flex;flex-direction:row;justify-content:center}'+
            '.zb-flex-row-around {display:flex;flex-direction:row;justify-content:space-around}'+
            '.zb-flex-row-between {display:flex;flex-direction:row;justify-content:space-between}'+
            '.zb-flex-row-right {display:flex;flex-direction:row;justify-content:flex-end}'+
            '.zb-flex-stretch {align-items:stretch}'+
            '.zb-flex-center {align-items:center}'+
            '.zb-flex-grow1 {flex-grow:1}'+
            '.zb-flex-nowrap {flex-wrap:nowrap}'+
            '.zb-text-center {text-align:center}'+
            '.zb-scroll-x {overflow-x:scroll; white-space: nowrap;}'+
            '.zb-scroll-x::-webkit-scrollbar {display:none}'+
            '.zb-scroll-y {overflow-y:scroll; white-space: nowrap;}'+
            '.zb-scroll-y::-webkit-scrollbar {display:none}'+
            '.zb-scroll{overflow:scroll; white-space: nowrap;}'+
            '.zb-scroll::-webkit-scrollbar {display:none}'+
            '.zb-width-r100{width:100%;}'+
            '.zb-height-r100{height:100%;}'+
            '#zbAsRadio{position:fixed;top:0;height:0;z-index:200;overflow:hidden;background-color:rgba(0,0,0,0.4);}'+
            '#zbAsRadio #zbASMask{}'+
            '#zbAsRadio #zbASBox{max-height:90%;background-color:#fff;border-top-left-radius:6px;border-top-right-radius:6px;}'+
            '#zbAsRadio #zbASTitle{height:40px;line-height:40px;font-size:20px;border-bottom:1px solid #eeeeee;}'+
            '#zbAsRadio #zbASBody{min-height:100px;}'+
            '#zbAsRadio .item_center{height:30px;margin:5px;text-align:center;border-bottom:1px solid #e8e8e8}'+
            '#zbAsRadio .item_left{height:30px;margin:5px;border-bottom:1px solid #e8e8e8}'+
            '#zbAsRadio .item_img{height:30px;width:30px;margin:5px;}'+
            '@keyframes bg_color {from{background:#eee;} to{background:#fff;}}'+
            '@-webkit-keyframes bg_color {from{background:#eee;} to{background:#fff;}}'
        ;

        let head = document.getElementsByTagName('head')[0];
        head.appendChild(style);
    }

    //覆盖指定id的dom元素
    this.replaceNode = function (id, node){
        let old = document.getElementById(id);
        let parent = old.parentNode;
        parent.replaceChild(node, old);
    }

    /**
     * 添加纵向列表数据
     * @param array data [{title:'aaa', value:'aaa', img:'', a:1, b2}] 或 [1,2,3]
     * @param object config 
     */
    this.addList = function(data, config={}) {
        let tplListItem = '<div class="zbas-list-item {item_class}" data-params="{params}">{title}</div>';
        let tplListItemImg = '<div class="zbas-list-item zb-flex-row-left zb-flex-center {item_class}" data-params="{params}"><img class="{item_img_class}" src="{img}">{title}</div>';

        let dataBody = document.getElementById('zbASBody');
        let strItems = '';
        for (let i=0; i<data.length; i++) {
            let item = data[i];
            if (this.isObject(item)) {
                // [{title:'aaa', value:'aaa', img:'', a:1, b2}]
                let tpl = (item['img'] !== undefined) ? tplListItemImg : tplListItem;
                strItems += this.repeatString(tpl, [data[i]], function(row){
                    let p = encodeURIComponent(JSON.stringify(row));
                    row['params'] = p;
                    row['item_class'] = config['item_class'] ? config['item_class'] : 'item_center';
                    row['item_img_class'] = config['item_img_class'] ? config['item_img_class'] : 'item_img';
                    return row;
                });
            } else {
                //[1,2,3]
                strItems += this.repeatString(tplListItem, [item], function(v){
                    let row = {title: v, value: v}
                    let p = encodeURIComponent(JSON.stringify(row));
                    row['params'] = p;
                    row['item_class'] = config['item_class'] ? config['item_class'] : 'item_center';
                    return row;
                });
            }
            
        }

        //渲染列表
        dataBody.innerHTML = strItems;

        //组装每一列, 添加事件绑定
        let items = dataBody.getElementsByClassName('zbas-list-item');
        for (let i=0; i<items.length; i++) {
            items[i].addEventListener('click', this.click.bind(this))
        }
    }

    //记录点击的list值
    this.click = function (e) {
        let obj = e.target;
        console.log(obj);
        
        if (this.confirm == 1) {
            return;
        } else {
            this.confirm = 1;
        }

        if (typeof this.onSelected == 'function') {
            let params = obj.getAttribute('data-params');
            this.hide();
            this.onSelected(this.decodeObj(params));
        }
        
        return true;
    }

    //根据数组, 渲染HTML字符串
    this.repeatString = function (tplDom, arr, func=null) {
        if (!tplDom.length) {
            this.error('字符串长度为空');
            return;
        }

        if (arr.length === 0) {
            this.error('数据为空');
            return tplDom;
        }

        let tpl = tplDom;
        let out = '';
        for (let i=0; i<arr.length; i++) {
            if (typeof func === 'function') {
                arr[i] = func(arr[i]);
            }
            let map = arr[i];
            let tmp = tpl;
            for (let j in map) {
                let re = new RegExp('{' + j + '}', 'g');
                tmp = tmp.replace(re, map[j]);
            }

            let re = new RegExp('{_idx}', 'g');
            tmp = tmp.replace(re, parseInt(i)+1);

            out += tmp;
        }

        return out;
    };

    //是否是数组
    this.isArray = function (o){
        return Object.prototype.toString.call(o) === '[object Array]';
    }

    this.isObject = function (o) {
        return Object.prototype.toString.call(o) === '[object Object]';
    }

    this.error = function(str) {
        console.log(str);
    }

    this.encodeObj = function (obj) {
        return encodeURIComponent(JSON.stringify(obj));
    }

    this.decodeObj = function (str) {
        return JSON.parse(decodeURIComponent(str));
    }
}
/**
 * 用法举例:

    let radio = new zbAsRadio();
    let title = 'this is title';

    // let data = [1,2,3,4,5,6,7,8,9,0];
    // let data = [{title:'a', value:1},{title:'b', value:2},{title:'c', value:3},{title:'d', value:4},{title:'e', value:5}];
    let data = [
        {title:'a', value:1, img:'summer/icons/right-arrow.png'},
        {title:'b', value:2, img:'summer/icons/right-arrow.png'},
        {title:'c', value:3, img:'summer/icons/right-arrow.png'},
        {title:'d', value:4, img:'summer/icons/right-arrow.png'},
        {title:'e', value:5}
    ];
    
    radio.init(title);
    radio.onSelected = function(params) {
        let str = JSON.stringify(params);
        document.getElementById('selected').innerText = str;
    }
    radio.addList(data, {item_class:'item_left', item_img_class:'item_img'}); //可选 item_center,item_left,item_img
    radio.show();
 */